package com.crm.quartz;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.crm.aop.SystemLogAspect;
import com.crm.model.ConsultInfoManage;
import com.crm.model.SysDepartment;
import com.crm.service.ConsultInfoManageService;
import com.crm.service.SysDepartmentService;

/**
 * @author hanlinxiu
 * 
 * 信息回流规则
 */
public class ConsultRedistributionJob {
	
	private static final Logger logger = Logger.getLogger(SystemLogAspect.class);
	
	@Autowired
	private ConsultInfoManageService consultInfoManageService;
	
	@Autowired
	private SysDepartmentService sysDepartmentService;
	
	public void execute(){  
		
		//查询所有（当前梯队*7）天为转报名或订座的信息量
		List<ConsultInfoManage> list = consultInfoManageService.selectRedistributionInfo();
		
		//得到每条信息量的当前所属梯队，根据信息量归属配置找到下一梯队，若没有找到下一梯队，则留在当前梯队。
		//若找到下一梯队，则需要更改信息量的创建时间
		//记录梯队的变更
		for(ConsultInfoManage record : list){
			
			//原归属部门
			String oDept = record.getDepartmentName2();
			String oCounselor = record.getCounselor();
			
			//查询下一梯队
			record = consultInfoManageService.getDepartmentId2FromRed(record);
			if(record != null){
				SysDepartment sd = sysDepartmentService.selectByPrimaryKey(record.getDepartmentId2());
				if(sd.getType()==3){
					record.setTypeFrom("3");
				}else{
					record.setTypeFrom("1");
				}
				//分配当前部门的人
				ConsultInfoManage cim = new ConsultInfoManage();
				cim = consultInfoManageService.getTopOne(record);
				if(cim!=null){
					if(cim.getCounselorId()!=null){
						record.setCounselorId(cim.getCounselorId());
						record.setCounselor(cim.getCounselor());
						record.setStatus(new Byte("2"));
					}
				}
				consultInfoManageService.updateByPrimaryKey(record);
				
				//新分配的归属部门
				String nDept = record.getDepartmentName2();
				String nCounselor = record.getCounselor();
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String cuurentDate = sdf.format(new Date());
				//找到了下一梯队  年-月-日 时:分:秒，信息量由oDept的oCounselor再分配到nDept的nCounselor
				logger.debug(cuurentDate + "，信息量" + record.getInfoManageId() + ",由" + oDept + "的" + oCounselor + "再分配到" + nDept + "的" + nCounselor);
			}
		}
	
    }
	
}
